import { Response } from 'express'
import createHttpError from 'http-errors'
import { MulterError } from 'multer'
import logger from './logger'

/** 请求成功 */
export function success(res: Response, message: string, data: any = {}, code: number = 200) {
  res.status(code).json({
    status: true,
    message,
    data,
  })
}

/** 请求失败 */
export function failure(
  res: Response,
  error: Error & { errors?: Error[] },
  message: string = '请求失败：',
) {
  let statusCode
  let errors: string | string[]
  if (
    error.name === 'SequelizeValidationError' ||
    error.name === 'SequelizeUniqueConstraintError'
  ) {
    // Sequelize验证错误
    statusCode = 400
    errors = (error.errors as Error[]).map((e: Error) => e.message)
  } else if (error.name === 'AggregateError') {
    // Sequelize bulkCreate验证错误
    statusCode = 400
    errors = (error.errors as Error[]).flatMap((e: any) => {
      return e.errors?.errors || e.message
    })
    errors = errors.map((e: any) =>
      Object.prototype.toString.call(e) === '[object Object]' ? e.message : e,
    )
  } else if (error.name === 'TokenExpiredError' || error.name === 'JsonWebTokenError') {
    // jwt token验证错误
    statusCode = 401
    errors = 'token错误或已过期'
  } else if (error instanceof createHttpError.HttpError) {
    // http-errors库创建的错误
    statusCode = error.status
    errors = error.message
  } else if (error instanceof MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      statusCode = 413
      errors = '文件大小超出限制(不高于5M)'
    } else {
      statusCode = 400
      errors = error.message
    }
  } else {
    statusCode = 500
    errors = '服务器错误。' + error.message
    logger.error('服务器错误。', error)
  }
  res.status(statusCode).json({
    status: false,
    message: `${message}${error.name}`,
    errors: Array.isArray(errors) ? errors : [errors],
  })
}
